/**
 * This file is part of 1genia trampoline
 * Copyright (C) 2007 1genia (contact@1genia.com)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of the License. 
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; see the file COPYING.TXT.  If not,
 * write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301, USA. 
 **/
package com.genia.toolbox.basics.bean;

import java.util.Collections;
import java.util.Comparator;
import java.util.Set;

/**
 * implementation of {@link java.util.Set} that is always sorted in respect to
 * the {@link Comparator} if one is given, or in respect to compareTo otherwise.
 * 
 * @param <V>
 *          the type of the elements of the {@link WeakSortedSet}.
 */
@SuppressWarnings("serial")
public class WeakSortedSet<V>
    extends AbstractWeakSortedCollection<V>
    implements Set<V>
{

  /**
   * constructor.
   */
  public WeakSortedSet()
  {
    super();
  }



  /**
   * constructor.
   * 
   * @param comparator
   *          the comparator to compare objects
   */
  public WeakSortedSet(Comparator<? super V> comparator)
  {
    super(comparator);
  }



  /**
   * Appends the specified element to the end of this list.
   * 
   * @param object
   *          element to be appended to this list.
   * @return <tt>true</tt> (as per the general contract of Collection.add).
   * @see java.util.ArrayList#add(java.lang.Object)
   */
  @Override
  public boolean add(V object)
  {
    int insertionPoint = Collections.binarySearch(this, object, comparator());
    if (insertionPoint >= 0) {

      int currentInsertionPoint = insertionPoint;
      while (insertionPoint >= 0 && comparator().compare(object, get(insertionPoint)) == 0) {
        if (object.equals(get(insertionPoint))) {
          set(insertionPoint, object);
          return false;
        }
        insertionPoint--;
      }
      insertionPoint = currentInsertionPoint;
      int size = size();
      while (insertionPoint < size && comparator().compare(object, get(insertionPoint)) != 0) {
        if (object.equals(get(insertionPoint))) {
          set(insertionPoint, object);
          return false;
        }
        insertionPoint++;
      }
    }
    else {
      insertionPoint = -insertionPoint - 1;
    }
    super.add(insertionPoint, object);
    return true;
  }

}
